<?php

namespace app\admin\controller;

use app\admin\constants\CacheConstants;
use app\model\AdminModel;
use app\model\AdminRulesModel;
use app\model\RequestLogModel;
use app\service\excel\ExcelService;
use Shopwwi\LaravelCache\Cache;
use support\Redis;
use support\Request;

class IndexController
{

    //首页获取统计信息
    public function getIndexData(Request $request){

         //获取最近七天的请求量
         $date_arr = [];
         $pv_arr = [];
 
         for($i = 15;$i>=0;$i--){
             $t = strtotime(date("Y-m-d 00:00:00",strtotime("- $i day")));
             
             $date_arr[] = date('Y-m-d',$t);
             $pv_arr[] = Cache::get('request_pv_'.$t) ?? 0;
         }
 
         //今日请求量
         $day_pv = Cache::get('request_pv_'.strtotime(date('Y-m-d 00:00:00')));
 
         //cpu核心数量
         $cpu_count = cpu_count();
 
         //启用进程数量
         $server_count = config('server.count');
 
         //站点总请求量
         $total_pv = Cache::get('request_pv_total');
 
         //上传附件配置
         $max_upload = bcdiv(config('server.max_package_size') / 1024,1024,0);
 
         //获取已上传附件总量
        //  $uploadsize = UploadFileModel::sum('size') ?? 0;
        //  $uploadsize = sprintf("%.3f",$uploadsize / 1024 / 1024).'M';
 
         //$os
         $os = PHP_OS;
 
         $mysql_version = \think\facade\Db::query('SELECT VERSION() as mysql_version')[0]['mysql_version'];
 
         //返回redis信息
         $handler = Redis::connection('default');
         $redis = $handler->info();
 
         //获取当前db的key总量
         $dbinfo = $redis['db'.getenv('RDS_DATABASE')];
         $keys = end(explode("=",explode(",",$dbinfo)[0]));
 
         $redis['keycount'] = $keys;
 

         return success('ok',[
            [
                'data_arr'=>$date_arr,
                'pv_arr'=>$pv_arr,
                'day_pv'=>(int)$day_pv,
                'cpu_count'=>(int)$cpu_count,
                'server_count'=>(int)$server_count,
                'total_pv'=>(int)$total_pv,
                'max_update'=>$max_upload,
                'os'=>$os,
                'mysql_version'=>$mysql_version,
                'reids_keycount'=>$redis['keycount'],
                'redis_used_memory_human'=>$redis['used_memory_human'],
                'php_version'=>PHP_VERSION
            ]
            
         ]);

    }

    //获取请求记录
    public function getRequestLog(Request $request){

        $params = $request->all();

        $requestlogModel = new RequestLogModel();

        $limit = $request->input('limit',$this->limit);

        $list = $requestlogModel->field("id,ip,method,action,route,controller,app,times,exception,create_time")->where(function($query) use ($params){
            // if($params['route']){
            //     $query->where("route",'like',"{$params['route']}%");
            // }
        })->order("id desc")->paginate($limit)->each(function($item,$key){

            $item->times = $item->times.'ms';
            
        });

        //$count = $list->total();
        return success('ok',$list);
    }

    //清空请求记录
    public function clearRequestLog(Request $request){

        RequestLogModel::getDB()->delete(true);

        return success('操作成功');
    }

    //导出请求记录
    public function exportRequestLog(Request $request){

        $list = RequestLogModel::field('id,ip,method,route,times,exception,create_time')->order("id desc")->limit(0,100000)->select();

        $excelService = new ExcelService();

        $res = $excelService->requestLogExport($list);
        
        return response()->download(runtime_path().'/'.$res,end(explode("/",$res)));
    }

    //获取管理员信息
    public function getAdminInfo(Request $request)
    {
        $admininfo = get_admin_info($request->admin_id);

        return success('ok',$admininfo);
    }

    //获取按钮权限(适配vben)
    public function getPermCode(){
        return success('ok',[]);
    }

    //获取管理员菜单列表
    public function getAdminMenuList(Request $request){
        $newlist = Cache::tags(CacheConstants::TAG_ADMIN_RULES_MENU)->get('admin_rules_menu_'.$request->admin_id);

        if(!$newlist){

            $rules = get_admin_rules_ids($request->admin_id);

            if(in_array('*',$rules)){
                $list = AdminRulesModel::where("type",1)
                ->order("sort desc")->column('*','id');
            }else{
                $list = AdminRulesModel::where("type",1)
                    ->where("id",'in',$rules)
                    ->order("sort desc")->column('*','id');
            }

            //数据组合

            $newlist = [];

            foreach($list as $k=>$v){

                $list[$k]['meta'] = [
                    'title'=>$v['title'],
                    'icon'=>$v['icon'],
                    'hideMenu'=>$v['hide_menu'] ? true:false,
                ];

                if($v['pid'] && $list[$v['pid']]){
                    //处理上级
                    $list[$v['pid']]['children'][] = &$list[$k];
                }else{
                    $newlist[] = &$list[$k];
                }

            }
            
            Cache::tags(CacheConstants::TAG_ADMIN_RULES_MENU)->set('admin_rules_menu_'.$request->admin_id,$newlist,CacheConstants::CACHE_TTL);
        }

        

        return success('ok',$newlist);

        $list = [
            [
                'path'=>'/dashboard',
                'name'=> 'Dashboard',
                'component'=> '/dashboard/analysis/index',
                'orderNo'=>100,
                'meta'=> [
                    'title'=> '首页',
                    'icon'=> 'bx:bx-home',
                    'hideMenu'=>false
                ],
                'children123'=>[
                    [
                        'path'=> 'workbench',
                        'name'=> 'workbench',
                        'component'=> '/dashboard/workbench/index',
                        'meta'=> [
                            'hideMenu'=> false,
                            'hideBreadcrumb'=> true,
                            'title'=>'workbench',
                            'currentActiveMenu'=>'/dashboard',
                            'icon'=> 'bx:bx-home',
                        ],
                    ],
                    [
                        'path'=> 'analysis',
                        'name'=> 'Analysis',
                        'component'=> '/dashboard/analysis/index',
                        'meta'=> [
                            'hideMenu'=> false,
                            'hideBreadcrumb'=> true,
                            'title'=>'分析页',
                            'currentActiveMenu'=>'/dashboard',
                            'icon'=> 'bx:bx-home',
                        ],
                    ],
                    
                ]
                ],
                ['path'=>'/analysis',
                'name'=> 'Dashboard2',
                'orderNo'=>300,
                'component'=> '/dashboard/analysis/index',
                //'redirect'=> '/dashboard/analysis',
                'meta'=> [
                    'title'=> '首页2',
                    'icon'=> 'bx:bx-home',
                ]]
        ];


    }

    //管理员修改密码
    public function updPassword(Request $request){

        $params = $request->post();

        if(!$params['password_new'] || !$params['password_old']){
            return error('参数错误');
        }

        $admin = new AdminModel();
        $admin = $admin->where("id",$request->admin_id)->find();

        if(get_password($params['password_old']) != $admin['password']){
            return error('旧密码错误');
        }

        $admin->password = get_password($params['password_new']);
        $admin->save();

        Cache::tags(CacheConstants::TAG_LOGIN_TOKEN)->delete('admin_token_'.$request->admin_token);

        return success('ok');
    }

    //退出登陆
    public function logout(Request $request){

        Cache::tags(CacheConstants::TAG_LOGIN_TOKEN)->delete('admin_token_'.$request->admin_token);

        return success('ok');
    }

}
